// Copyright (c) 2022 CHANGLEI. All rights reserved.

import 'package:aircraft_war/bloc/bloc_listenable.dart';
import 'package:aircraft_war/bloc/game_alive_cubit.dart';
import 'package:aircraft_war/commons/fonts.dart';
import 'package:aircraft_war/components/main_game.dart';
import 'package:aircraft_war/generated/assets.dart';
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flame/flame.dart';
import 'package:flutter/cupertino.dart';

final _sprite = Sprite(Flame.images.fromCache(Images.life));
final _spriteSize = Vector2(30 * 102 / 126, 30);
final _textPaint = TextPaint(
  style: const TextStyle(
    color: CupertinoColors.label,
    fontSize: 20,
    fontWeight: FontWeight.w500,
    fontFamily: handwritten,
  ),
);

/// Created by changlei on 2022/5/18.
///
/// 生命值
class AliveValue extends PositionComponent with BlocListenable<GameAliveCubit, int>, HasGameRef<MainGame> {
  int? _value;
  Vector2? _parentSize;

  /// 设置值
  set value(int value) {
    if (_value == value) {
      return;
    }
    _value = value;
    if (_parentSize != null) {
      layout(_parentSize!);
    }
  }

  @override
  Future<void> onLoad() async {
    onNewState(gameRef.aliveCubit.state);
  }

  @override
  void render(Canvas canvas) {
    if (gameRef.aliveCubit.isMin) {
      return;
    }
    _sprite.render(
      canvas,
      size: _spriteSize,
    );
    if (_value != null) {
      _textPaint.render(canvas, 'x $_value', Vector2(_spriteSize.x + 10, 0));
    }
  }

  /// 布局
  void layout(Vector2 parentSize) {
    _parentSize = parentSize;
    if (!isMounted || gameRef.aliveCubit.isMin) {
      size = Vector2.zero();
    } else {
      size = Vector2(_spriteSize.x, 30);
      if (_value != null) {
        size += Vector2(_textPaint.measureTextWidth('x $_value') + 10, 0);
      }
    }
    position = Vector2(parentSize.x - 20 - size.x, 20);
  }

  @override
  void onNewState(int state) {
    value = state;
  }
}
